package com.hnevc.foodserver.service;


import com.hnevc.foodserver.bean.News;
import com.hnevc.foodserver.dao.NewsDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class NewsService {
    @Autowired
    NewsDao newsDao;

    public List<News> list() {
        List<News> all = newsDao.findAll();
        return all;
    }

    public News findone(News news) {
        News news1 = newsDao.findOne(Example.of(news)).orElse(null);
        return news1;
    }

    public List<News> findByType(News news) {
        Sort sort = Sort.by(Sort.Direction.DESC, "id");
        return newsDao.findAll(Example.of(news), sort);
    }

    public Page<News> listByPage(PageRequest pageRequest) {
        return newsDao.findAll(pageRequest);
    }

    public News add(News news) {
        News save = newsDao.save(news);
        return save;
    }

    public News deleteById(News news) {
        try{
            newsDao.deleteById(news.getId());
            return news;
        }catch (Exception e){
            return null;
        }

    }
}
